package com.xbjtech.vipsystem.utils;

import com.xbjtech.vipsystem.po.User;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.lettuce.core.output.StatusOutput;
import sun.security.rsa.RSAPrivateCrtKeyImpl;
import sun.security.rsa.RSAPublicKeyImpl;

import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

/**
 * @author leejun.happy@gmail.com
 * @created 2019-07-22
 */
public class JwtUtils {

    private static final String JWT_SUBJECT = "VIPSYSTEM";
    private static final String PRIVATE_KEY_ENCODING = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCLY3z1ozNaRyju2ph67MZXmNMSBPG3kAmTVAE2bEhYoGgW3INsFfn3HYcV67dL+gSv0dgmnA+wPxof8pXLLSfewvJUBPF+thwenzBl81lvxejDMm3y39VSiR149/nEw9xPxhgkVZjpKhv7T7doZ6Dm64GK/eqbNsd/2SkzRPfbidw9WV39rPsdVo9apSg7swPwB3M5WXRVHH652n3nYgSSVK1djc7TpQ3iLKmt24uhjFtVJ8lwCERAqIiszV7CnURbqeuyQGeDycO31i64PEbM4e2g/SjdU9pzJefp1OF6qKYrtq3oZItM3HJRvqJ8as7IgQNMIH3eoIwm7L307EFFAgMBAAECggEAZ0Wy05uy9HQ8k5tJ1emPml8UIwmevU3uikV3EIdxophWBnoitPYjWT97UnZuO9BloI5tA04lIYPfK0RkT0CJhbYSLMXs1uC+PMHc7ew6m2GabuTyKTxFpP0J5RJ075/dnw053dG9lSMp0Czjymrc/7oFJKG0LIONk9+lcuLqcLC9YxB+F5iBwfOg8Y15fsUBvSPHLxs6+cTF9pRqsdQCspWOfAmbXtnv8oiSaHG7TzVpQW7/pFvzMdCYjf7vHoUFJSojKKO2VWGVcbCl8GaWTy6Bihk2Oza/e+NJrfg/OTcrhObRLstqo1DkXcUl18yJ/Viz5FHW/49AUjETX5ZUgQKBgQDWTc2ZAzCbQLoAtcD6jhtgm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0T324ncPVld/az7HVaPWqUoO7MD8AdzOVl0VRx+udp952IEklStXY3O06UN4iyprduLoYxbVSfJcAhEQKiIrM1ewp1EW6nrskBng8nDt9YuuDxGzOHtoP0o3VPacyXn6dTheqimK7at6GSLTNxyUb6ifGrOyIEDTCB93qCMJuy99OxBRQIDAQAB";

    /**
     * 私钥
     */
    private static PrivateKey JWT_PRIVATE_KEY = null;

    static {
        try {
            JWT_PRIVATE_KEY = RSAPrivateCrtKeyImpl.newKey(Base64.getDecoder().decode(PRIVATE_KEY_ENCODING));
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
    }

    /**
     * 公钥
     */
    private static PublicKey JWT_PUBLIC_KEY = null;

    static {
        try {
            JWT_PUBLIC_KEY = new RSAPublicKeyImpl(Base64.getDecoder().decode(PUBLIC_KEY_ENCODING));
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
    }


    /**
     * 签发token
     *  想把username封装到token里
     * @return token字符串
     */
    public static String sign(String username, String shopId) {
        String jws = Jwts.builder()
                .claim("username", username)
                .claim("shopId", shopId)
                .setSubject(JWT_SUBJECT)
                .signWith(JWT_PRIVATE_KEY)
                .compact();
        return jws;
    }

    /**
     * 验证token的方法
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        try {
            Jwts.parser().requireSubject(JWT_SUBJECT).setSigningKey(JWT_PUBLIC_KEY).parseClaimsJws(token);
            return true;
        } catch(MissingClaimException mce) {
            System.out.println(mce.getMessage());
        } catch(IncorrectClaimException ice) {
            System.out.println(ice.getMessage());
        } catch (JwtException e) {
            System.out.println(e.getMessage());
        }
        return false;
    }

    /**
     * 
     * @param token
     * @return
     */
    public static User getUserFromToken(String token) {
        try {
            Claims body = Jwts.parser().setSigningKey(JWT_PUBLIC_KEY).parseClaimsJws(token).getBody();
            String username = body.get("username", String.class);
            String shopId = body.get("shopId", String.class);
            User user = new User();
            user.setUsername(username);
            user.setShopId(shopId);
            return user;
        } catch(MissingClaimException mce) {
            System.out.println(mce.getMessage());
        } catch(IncorrectClaimException ice) {
            System.out.println(ice.getMessage());
        } catch (JwtException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    public static void main(String[] args) {
        String token = sign("buyer", "001");
        System.out.println(token);

    }


}
